#!/usr/bin/env python
# _*_ coding:utf-8 _*_
#
# Copyright(c) http://m.ecpark.cn/
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
try:
    try:
        from pymongo import MongoClient as Connection
        from pymongo.errors import DuplicateKeyError
    except ImportError:
        from pymongo import Connection
    from pymongo.errors import ConnectionFailure, AutoReconnect, DuplicateKeyError
except ImportError:
    raise ImportError("Can't import pymongo. "
                      "See http://api.mongodb.org/python/current/ "
                      "for instructions on how to install pymongo.")


def get_master_connect(mongodb_instance_list, username='root', password="", auth_source='admin'):
    try:
        for mongo_instance in mongodb_instance_list:
            host = mongo_instance.split(':')[0]
            port = int(mongo_instance.split(':')[1])
            mongo_connect = Connection(host=host, port=port, username=username, password=password,
                                       authSource=auth_source)
            if mongo_connect.is_mongos:
                return mongo_connect
            elif mongo_connect.is_primary:
                return mongo_connect
    except Exception as e:
        raise ("Connect Error on {}".format(str(mongodb_instance_list)))
    return


def get_connect(host='127.0.0.1', port=27001, username='root', password="", auth_source='admin'):
    # try:
    mongo_connect = Connection(host=host, port=port, username=username, password=password, authSource=auth_source)
    # except Exception as e:
    #     raise ("Connect Error on {}:{}".format(host, port))
    return mongo_connect


def mongo_connect_replset(connect_instance_list, username='mongodb_backup', auth_source='admin', password="",
                          read_preference='secondaryPreferred'):
    # try:
    mongo_connect = Connection(host=connect_instance_list, username=username, password=password,
                               authSource=auth_source, readPreference=read_preference)
    # except Exception as e:
    #     raise ("Connect Error on {}:{}".format(host, port))
    return mongo_connect
